package yu.code.yurpc.handler;


import cn.hutool.core.lang.Dict;
import cn.hutool.setting.yaml.YamlUtil;
import yu.code.yurpc.config.RpcConfig;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * yml/yaml 配置文件解析器
 */
public class YamlHandler implements ConfigHandler {
    @Override
    public <T> T loadConfig(Class<T> tClass, String filePath) {
        Dict dict = YamlUtil.loadByPath(filePath);
        return dict.toBean(tClass);
    }

    @Override
    public <T> T loadConfig(Class<T> tClass, String prefix, String filePath) {
        Dict dict = YamlUtil.loadByPath(filePath);
        Map<String, Object> map = (Map<String, Object>) dict.get(prefix);
        try {
            return setAttrs(map, tClass);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

    private <T> T setAttrs(Map<String, Object> map, Class<T> tClass) throws InstantiationException, IllegalAccessException {
        T t = tClass.newInstance();
        for (Field declaredField : tClass.getDeclaredFields()) {
            Object value = map.get(declaredField.getName());
            if (map.containsKey(declaredField.getName())) {
                declaredField.setAccessible(true);
                Class<?> fieldType = declaredField.getType();
                if (!fieldType.isInstance(value)){
                    // 如果值的类型与字段声明的类型不匹配，则尝试转换
                    value = convertValue(value, fieldType);
                }
                declaredField.set(t, map.get(declaredField.getName()));
            }
        }
        return t;
    }
    private  Object convertValue(Object value, Class<?> targetType) {
        if (targetType == Integer.class || targetType == int.class) {
            return Integer.parseInt((String) value);
        } else if (targetType == Double.class || targetType == double.class) {
            return Double.parseDouble((String) value);
        } else if (targetType == Float.class || targetType == float.class) {
            return Float.parseFloat((String) value);
        } else if (targetType == Long.class || targetType == long.class) {
            return Long.parseLong((String) value);
        } else if (targetType == Boolean.class || targetType == boolean.class) {
            return Boolean.parseBoolean((String) value);
        } else if (targetType == String.class) {
            return value.toString();
        } else {
            throw new IllegalArgumentException("不支持的类型转换: " + value.getClass() + " to " + targetType);
        }
    }
}

